<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ChatAI</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
            margin: 0;
            background: #f0f2f6;
        }
        .container {
            display: flex;
            height: 100vh;
        }
        .sidebar {
            width: 240px;
            background: white;
            padding: 20px;
            box-shadow: 2px 0 8px rgba(0,0,0,0.1);
        }
        .settings-card {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
        }
        .history-card {
            margin-top: 20px;
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
        }
        .hidden {
            display: none;
        }
        .main {
            flex: 1;
            padding: 30px;
            background: #f0f2f6;
        }
        .header {
            margin-bottom: 20px;
        }
        .chat-container {
            background: white;
            border-radius: 8px;
            padding: 20px;
            height: 65vh;
            overflow-y: auto;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }
        .message {
            margin: 10px 0;
            padding: 12px 16px;
            border-radius: 12px;
            max-width: 70%;
        }
        .message.user {
            background: #e3f2fd;
            margin-left: auto;
        }
        .message.assistant {
            background: #f1f3f4;
        }
        .icon-button {
            background: none;
            border: none;
            font-size: 14px;
            cursor: pointer;
            padding: 5px;
        }
        .primary-button {
            background: #1a73e8;
            color: white;
            border: none;
            padding: 12px 24px; /* 增大按钮尺寸 */
            border-radius: 6px;
            cursor: pointer;
            transition: background 0.2s;
            font-size: 12px; /* 调整字体大小 */
        }
        .primary-button:disabled {
            background: #8ab4f8;
            cursor: not-allowed;
        }
        .secondary-button {
            background: #f8f9fa;
            color: #1a73e8;
            border: 1px solid #dadce0;
            padding: 12px 24px; /* 增大按钮尺寸 */
            border-radius: 6px;
            cursor: pointer;
            margin-top: 10px;
            font-size: 12px; /* 调整字体大小 */
        }
        .form-control {
            width: 100%;
            padding: 10px;
            border: 1px solid #dadce0;
            border-radius: 6px;
            margin: 5px 0;
        }
        .input-area {
            display: flex;
            gap: 10px;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 侧边栏 -->
        <div class="sidebar">
            <div class="settings-card">
                <button id="settings-toggle" class="icon-button">⚙️ 设置</button>
                <div id="settings-content" class="hidden">
                    <div class="form-group">
                        <label for="address">选择地址</label>
                        <select id="address" class="form-control">
                            <option value="Ollama">Ollama</option>
                            <option value="LMstudio">LMstudio</option>
                            <option value="AiGitee">AiGitee</option>
                            <option value="ChatGLM">ChatGLM</option>
                            <option value="THUds">THUds</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="api-key">API Key</label>
                        <input type="password" id="api-key" class="form-control" placeholder="输入 API Key">
                    </div>
                    <div class="form-group">
                        <label for="model">选择模型</label>
                        <select id="model" class="form-control"></select>
                    </div>
                    <div class="form-group">
                        <label for="temperature">温度参数</label>
                        <input type="range" id="temperature" min="0" max="1" step="0.05" value="0.7">
                        <span id="temperature-value">0.7</span>
                    </div>
                </div>
            </div>
            <button id="new-chat" class="primary-button">🆕 新建会话</button>
            <button id="save-chat" class="secondary-button">💾 保存对话</button>
            <div class="history-card">
                <!-- <h3>📜 历史记录</h3> -->
                <ul id="history-list"></ul>
            </div>
        </div>
        <div class="main">
            <div class="header">
                <h3>🤖 多模型聊天应用</h3>
                <!-- <p>与不同模型的 AI 聊天，搞笑幽默一些</p> -->
            </div>
            <div id="chat-window" class="chat-container"></div>
            <div class="input-area">
                <input type="text" id="user-input" class="form-control" placeholder="请输入你的消息">
                <button id="submit-button" class="primary-button">提交</button>
            </div>
        </div>
    </div>
    <script>
    document.addEventListener("DOMContentLoaded", function () {
        const settingsToggle = document.getElementById("settings-toggle");
        const settingsContent = document.getElementById("settings-content");
        const addressSelect = document.getElementById("address");
        const modelSelect = document.getElementById("model");
        const temperatureInput = document.getElementById("temperature");
        const temperatureValue = document.getElementById("temperature-value");
        const newChatButton = document.getElementById("new-chat");
        const saveChatButton = document.getElementById("save-chat");
        const historyList = document.getElementById("history-list");
        const chatWindow = document.getElementById("chat-window");
        const userInput = document.getElementById("user-input");
        const submitButton = document.getElementById("submit-button");

        const ADDRESSES = {
            "Ollama": {
                "base_url": "http://localhost:11434/v1",
                "models": [ "qwen2.5:3b", "glm4", "llama3.2", "phi", "phi3", "deepseek-r1:1.5b", "mistral:7b-instruct-q2_k"]
            },
            "LMstudio": {
                "base_url": "http://localhost:12345/v1",
                "models": ["qwen2.5-instructv2-7b", "qwen-chatv2-7b", "deepseek-r1-qwen-7b"]
            },
            "AiGitee": {
                "base_url": "https://ai.gitee.com/api/v1",
                "models": [
                    "Qwen2-7B-Instruct", "Qwen2.5-72B-Instruct", "Qwen2.5-14B-Instruct", "Qwen2.5-7B-Instruct",
                    "Qwen2-72B-Instruct", "Qwen2-7B-Instruct", "Qwen2-32B-Instruct", "QwQ-32B-Preview", "Yi-34B-Chat", "glm-4-9b-chat"
                ]
            },
            "ChatGLM": {
                "base_url": "https://open.bigmodel.cn/api/paas/v4",
                "models": ["glm-4-flash"]
            },
            "THUds": {
                "base_url": "https://madmodel.cs.tsinghua.edu.cn/v1",
                "models": ["DeepSeek-R1-Distill-32B", "DeepSeek-R1-671B"]
            }
        };

        let currentConversation = [];
        let currentConversationTitle = null;
        let chatHistory = [];

        // 初始化设置
        settingsToggle.addEventListener("click", () => {
            settingsContent.classList.toggle("hidden");
        });

        addressSelect.addEventListener("change", () => {
            const selectedAddress = addressSelect.value;
            const models = ADDRESSES[selectedAddress].models;
            modelSelect.innerHTML = models.map(model => `<option value="${model}">${model}</option>`).join("");
        });

        temperatureInput.addEventListener("input", () => {
            temperatureValue.textContent = temperatureInput.value;
        });

        // 初始化模型列表
        addressSelect.dispatchEvent(new Event("change"));
        submitButton.disabled = false;
        userInput.disabled = false;

        // 新建会话
        newChatButton.addEventListener("click", () => {
            if (currentConversation.length > 0) {
                const title = `${currentConversation[1].content.substring(0, 10)} - ${new Date().toLocaleString()}`;
                saveConversation(title, currentConversation);
            }
            currentConversationTitle = null;
            currentConversation = [];
            chatHistory = [];
            submitButton.disabled = false;
            userInput.disabled = false;
            renderChatWindow(); // 清空聊天区
            loadHistory();      // 刷新历史记录
        });

        // 保存对话为 CSV 文件（兼容中文）
        saveChatButton.addEventListener("click", () => {
            if (chatHistory.length === 0) {
                alert("没有可保存的对话内容！");
                return;
            }
            const csvContent = "角色,内容\n" + chatHistory.map(msg => `${msg.role},${msg.content}`).join("\n");
            const blob = new Blob(["\uFEFF" + csvContent], { type: "text/csv;charset=utf-8;" }); // 添加 BOM 头
            const url = URL.createObjectURL(blob);
            const a = document.createElement("a");
            a.href = url;
            a.download = "chat_history.csv";
            a.click();
            URL.revokeObjectURL(url);
        });

        // 加载历史记录
        function loadHistory() {
            const history = JSON.parse(localStorage.getItem("chatHistory") || []);
            historyList.innerHTML = history
                .sort((a, b) => new Date(b.time) - new Date(a.time)) // 按时间逆序排列
                .map(conv => `<li>${conv.title}</li>`)
                .join("");
        }

        // 保存对话到 localStorage
        function saveConversation(title, messages) {
            const history = JSON.parse(localStorage.getItem("chatHistory") || []);
            history.push({ title, time: new Date().toLocaleString(), messages });
            localStorage.setItem("chatHistory", JSON.stringify(history));
            loadHistory();
        }

        // 渲染聊天窗口
        function renderChatWindow() {
            chatWindow.innerHTML = chatHistory.map(msg => `
                <div class="message ${msg.role}">
                    ${msg.content}
                </div>
            `).join("");
            // 自动滚动到底部
            chatWindow.scrollTop = chatWindow.scrollHeight;
        }

        // 提交消息逻辑（添加按钮禁用）
        function submitMessage() {
            const userMessage = userInput.value;
            if (!userMessage) return;

            // 禁用按钮和输入框
            submitButton.disabled = true;
            // userInput.disabled = true;

            currentConversation.push({ role: "user", content: userMessage });
            chatHistory.push({ role: "user", content: userMessage });
            renderChatWindow();

            const payload = {
                model: modelSelect.value,
                messages: currentConversation,
                // stream: true,
                stream:false,
                temperature: parseFloat(temperatureInput.value)
            };

            const headers = {
                "Authorization": `Bearer ${document.getElementById("api-key").value}`,
                "Content-Type": "application/json"
            };

            fetch(`https://cors-anywhere.herokuapp.com/${ADDRESSES[addressSelect.value].base_url}/chat/completions`, {
            // fetch(`${ADDRESSES[addressSelect.value].base_url}/chat/completions`, {
                method: "POST",
                headers: headers,
                body: JSON.stringify(payload)
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`API 响应失败! 状态码: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    const assistantMessage = data.choices[0].message.content;
                    currentConversation.push({ role: "assistant", content: assistantMessage });
                    chatHistory.push({ role: "assistant", content: assistantMessage });
                    renderChatWindow();
                })
                .catch(error => {
                    console.error("请求发送失败:", error);
                    alert(`请求发送失败: ${error.message}`);
                })
                .finally(() => {
                    // 无论成功与否，重新启用
                    submitButton.disabled = false;
                    // userInput.disabled = false;
                });

            userInput.value = "";
        }

        // 提交按钮和回车键事件
        submitButton.addEventListener("click", submitMessage);
        userInput.addEventListener("keypress", (e) => {
            if (e.key === "Enter") {
                submitMessage();
            }
        });

        // 初始化加载历史记录
        loadHistory();
    });

    </script>

</body>
</html>
